<?php

/**
 * Category actions.
 *
 * @package    ProdAssistant
 * @subpackage Category
 * @author     Paweł Świtalla
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class CategoryActions extends sfActions
{
  private $core;
  public function preExecute()
  {
    $this->core = PACore::getInstance();
  }
  
  public function executeCreate(sfWebRequest $request)
  {
    $this->form = new CategoryForm();
    $url = $this->core->generateAppUrl('Core', 'categoriesSettings');
    
    if($request->isMethod('post'))
    {
      $parameters = $request->getParameter('category');
      if(!empty($parameters['locked']))
      {
        $locked = $parameters['locked'] == "true" ? : false;
      }
      
      if($parameters['parentCategory'] == '')
      {
        $root = Doctrine_Query::create()
                ->select('c.*')
                ->from('Category c')
                ->where('c.parentCategory IS NULL')
                ->fetchOne();
                
        if($root instanceof Category)
        {
          if($request->isXmlHttpRequest())
          {
            $this->getResponse()->setContent('error@Podaj kategorię nadrzędną.#');
            return sfView::NONE;
          }
          else
          {
            $this->getUser()->setFlash('info', 'Nieprawidłowa kategoria nadrzędna');
            $this->redirect($url);
          }
        }
      }
      elseif($parameters['parentCategory'] != '' && !$locked){
        $this->form->setValidator('quantityUnit', new sfValidatorString());
      }
      
      $this->form->bind($parameters);
      if($this->form->isValid())
      {
        $cat = $this->form->save();
        $parent = Doctrine_Core::getTable('Category')->find($cat->getParentCategory());
        if($parent instanceof BaseCategory)
        {
          $cat->setLevel($parent->getLevel() + 1);
          $cat->setItemsCount(0);
          $cat->save();
        }
        if($request->isXmlHttpRequest())
        {
          $this->getResponse()->setContent('location@'.$url."#");
          return sfView::NONE;
        }
        else $this->redirect($url);
      }
    }
    if($request->isXmlHttpRequest())
    {
      $errors = '';
      foreach($this->form->getFormFieldSchema() as $field){
        if($field->hasError()){
          $errors .= ucfirst($field->getName()).': '.$field->getError()."\n";
        }
      }
      $this->getResponse()->setContent('error@'.$errors."#");
      return sfView::NONE;
    }
    else $this->referer = $url;
  }
  
  public function executeDelete(sfWebRequest $request)
  {
    $id = $request->getParameter('id');
    $delete = Doctrine_Query::create()
            ->delete()
            ->from('Category')
            ->where('id = ?', $id)
            ->execute();
    $this->redirectIf($delete, $this->core->generateAppUrl('Core', 'categoriesSettings'));
  }
  
  public function executeUpdate(sfWebRequest $request)
  {
    $item_id = $request->getParameter('id');
    $record = Doctrine_Core::getTable('Category')->find($item_id);
    $this->form = new CategoryForm($record);
    $url = $this->core->generateAppUrl('Core', 'categoriesSettings');
    
    if($request->isMethod('put'))
    {
      $this->form->bind($request->getParameter('category'));
      if($this->form->isValid())
      {
        $cat = $this->form->save();
        $parent = Doctrine_Core::getTable('Category')->find($cat->getParentCategory());
        if($parent instanceof BaseCategory)
        {
          $cat->setLevel($parent->getLevel() + 1);
          $cat->save();
        }
        if($request->isXmlHttpRequest())
        {
          $this->getResponse()->setContent('location@'.$url."#");
          return sfView::NONE;
        }
        else $this->redirect($url);
      }
    }
    if($request->isXmlHttpRequest())
    {
      $errors = '';
      foreach($this->form->getFormFieldSchema() as $field){
        if($field->hasError()){
          $errors .= ucfirst($field->getName()).': '.$field->getError()."\n";
        }
      }
      $this->getResponse()->setContent('error@'.$errors."#");
      return sfView::NONE;
    }
    else $this->referer = $url;
  }
  
  public function executeItemList(sfWebRequest $request)
  {
    $categoryName = $request->getParameter('categoryName') ? $request->getParameter('categoryName') : 'Magazyn';
    
    $category = '';
    try
    {
      $categoryTable = Doctrine_Core::getTable('Category');
      if($categoryName)
      {
        $category = $categoryTable->createQuery('c')
              ->select('name')
              ->where('c.name = ?', $categoryName)
              ->fetchOne();
      }
      else
      {
        $category = $categoryTable->createQuery('c')
              ->select('level')
              ->where('c.level = ?', 0)
              ->fetchOne();
      }
    }
    catch(Doctrine_Exception $e)
    {
      $this->error = 'Exception: '.$e->getMessage();
      $this->setTemplate(PACore::getErrorTemplatesDir().'default');
      return sfView::ERROR;
    }
    
    if($category instanceof Doctrine_Record)
    {
      $sortByFirst = $request->getParameter('sortByFirst') == '' ? 'name' : $request->getParameter('sortByFirst');
      $sortBySecond = $request->getParameter('sortBySecond') == '' ? 'quantity' : $request->getParameter('sortBySecond');
      $sortBy = array($sortByFirst, $sortBySecond);
      $sortOrder = $request->getParameter('sortOrder') == '' ? 'ASC' : $request->getParameter('sortOrder');
      
      // Dla dziedziczenia itemów getCategoryItemsList - jeśli nie to getCategoryItems
      //$this->items = $category->getCategoryItemsListQuery($sortBy, $sortOrder)->execute();
      
      $maxPerPage = Settings::getSettings('items_per_page', $this->getUser()->getAttribute('userObject')) ? : 15;
      
      $this->pager = new PAPager(
        'StoreItem',
        $maxPerPage
      );
      
      $this->pager->setQuery($category->getCategoryItemsListQuery($sortBy, $sortOrder));
      if($request->hasParameter("objectPage")){
        $page = $this->pager->getPageForObject($request->getParameter("objectPage"), $category, $sortBy, $sortOrder);
        $this->pager->setPage($page);
        $this->getUser()->setFlash("objectPage", "background-color: #212121");
      }
      else $this->pager->setPage($request->getParameter('page', 1));
      $this->pager->init();
      
      $this->items = $this->pager->getResults();
      $this->category = $category;
      $this->getUser()->setAttribute("categoryObject", $this->category);
      
      if($this->category instanceof Category){
        $this->quantityUnit = $category->getQuantityUnit();
        $this->columns = $category->getParametersHierarchy();
        $this->parametersCount = $this->columns->count();
        $this->itemsExtraFields = array();
        
        // Ładowanie wartości kolumn dodatkowych (parameters)
        StoreItem::fillExtraFields($this->items, $this->columns, $this->itemsExtraFields);
      }
    }
    else
    {
      $this->error = 'Nie odnaleziono podanej kategorii.';
      $this->setTemplate(PACore::getErrorTemplatesDir().'default');
      return sfView::ERROR;
    }
  }
  
  public function executeItemListProxy(sfWebRequest $request)
  {
    $categoryName = $request->getParameter('categoryName');
    $sortByFirst = $request->getParameter('sortByFirst');
    $sortBySecond = $request->getParameter('sortBySecond');
    $sortOrder = $request->getParameter('sortOrder');
    $this->redirect(
                      $this->core->generateAppUrl(
                                                  'Store',
                                                  'categoryItemsList',
                                                  true,
                                                  array(
                                                        'categoryName' => $categoryName,
                                                        'sortByFirst' => $sortByFirst,
                                                        'sortBySecond' => $sortBySecond,
                                                        'sortOrder' => $sortOrder
                                                        )
                                                 )
                     );
  }
}
